package com.angel.architecture.initializer.injector.impl;

import java.lang.reflect.Field;

import org.apache.log4j.Logger;

import com.angel.architecture.flex.locator.ObjectLocator;
import com.angel.architecture.initializer.injector.Injector;
import com.angel.common.helpers.AnnotationHelper;
import com.angel.common.helpers.ReflectionHelper;
import com.angel.common.helpers.StringHelper;
import com.angel.data.generator.annotations.Inject;

/**
 *
 * @author William
 *
 */
public class InjectInjector extends Injector {

	private static final Logger LOGGER = Logger.getLogger(InjectInjector.class);

	@Override
	public boolean applies(Field field) {
	    Class<?> fieldType = field.getType();
	    boolean hasInjectAnnotation = AnnotationHelper.hasAnnotation(field, Inject.class);
	    boolean applies = hasInjectAnnotation;
	    if(hasInjectAnnotation){
	    	Inject inject = AnnotationHelper.getAnnotation(field, Inject.class);
	    	if(StringHelper.isEmpty(inject.beanName())){
	    		applies = ObjectLocator.contains(fieldType);
	    	} else {
	    		applies = ObjectLocator.contains(inject.beanName());
	    	}
	    }
	    return applies;
	}

	@Override
	protected void doInject(Field field, Object object) {
	    Class<?> fieldType = field.getType();
	    Inject inject = AnnotationHelper.getAnnotation(field, Inject.class);
	    Object bean = null;
	    if(StringHelper.isEmpty(inject.beanName())){
	    	bean = ObjectLocator.get(fieldType);
	    } else {
	    	bean = ObjectLocator.getBeanByName(inject.beanName());
	    }
	    LOGGER.debug("Injecting service " + fieldType.getSimpleName() + " on object " + object);
	    field.setAccessible(true);
	    ReflectionHelper.setFieldValue(object, field, bean);
	    field.setAccessible(false);
	}

}
